package com.usian.mq;


import com.usian.JsonUtils;
import com.usian.mapper.LocalMessageMapper;
import com.usian.pojo.LocalMessage;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.UUID;

@Component
public class MQSender implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {

    @Autowired
    private LocalMessageMapper localMessageMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;

    /**
     * confirm 消息回调
     * @param correlationData
     * @param b
     * @param s
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        String txNo = correlationData.getId();
        //b  true  成功  反之  false 失败
        if(b){
            LocalMessage localMessage = new LocalMessage();
            localMessage.setTxNo(txNo);
            localMessage.setState(1); //0 失败 1 成功
            localMessageMapper.updateByPrimaryKeySelective(localMessage);
        }

    }

    @Override
    public void returnedMessage(Message message, int i, String s, String s1, String s2) {
        System.out.println("return--message:" + new String(message.getBody())
                + ",exchange:" + s + ",routingKey:" + s1);
    }

    /**
     * 封装消息发送，开启回调的基础上消息发送
     * @param localMessage
     */
    public void sendMsg(LocalMessage localMessage){

        RabbitTemplate rabbitTemplate = (RabbitTemplate) this.amqpTemplate;
        rabbitTemplate.setConfirmCallback(this);//确认回调
        rabbitTemplate.setReturnCallback(this);//失败回退

        CorrelationData correlationData = new CorrelationData(localMessage.getTxNo());
        rabbitTemplate.convertAndSend("order_exchage","order.add",
                JsonUtils.objectToJson(localMessage),correlationData);
    }
}
